//
//  AfnHelper.m
//  afn
//
//  Created by 杨少锋 on 15/10/5.
//  Copyright © 2015年 杨少锋. All rights reserved.
//

#import "AfnHelper.h"
#import "MBProgressHUD.h"
#import "AFNetworking.h"


@interface AfnHelper()

// 菊花视图
@property (nonatomic, strong) MBProgressHUD *hud;
// 请求类本身
@property (nonatomic, strong) AfnHelper *helper;

@end


@implementation AfnHelper

// get请求
//参数的意思  url:get请求的链接  dic:拼接的参数 sucess:成功的block  faile:失败的block
+ (void)getDataWithUrl:(NSString *)url dic:(NSDictionary *)dic sucess:(void(^)(id opreation))sucess  faile:(void(^)(id error))faile {
    [[[AfnHelper alloc] init].hud show:YES];
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    [mgr GET:url parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [[[AfnHelper alloc] init].hud hide:YES];
        [[[AfnHelper alloc] init].hud removeFromSuperview];
        sucess(responseObject);
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        [[[AfnHelper alloc] init].hud hide:YES];
        [[[AfnHelper alloc] init].hud removeFromSuperview];
        faile(error);
    }];
}

// post请求
+ (void)postDataWithUrl:(NSString *)url dic:(NSDictionary *)dic sucess:(void(^)(id opreation))sucess  faile:(void(^)(id error ))faile {
    [[[AfnHelper alloc] init].hud show:YES];
       AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    // 发送的是json格式数据
    // *AFHTTPRequestSerializer(二进制)
    // *AFJSONRequestSerializer(JSON)
    // *AFPropertyListRequestSerializer(Plist)
    mgr.requestSerializer = [AFJSONRequestSerializer serializer];
    // 返回的格式的也是json格式(xml需要自己解析)
    //AFHTTPResponseSerializer(二进制)
    //*AFJSONResponseSerializer(JSON)
    //*AFPropertyListResponseSerializer(Plist)
    //*AFXMLParserResponseSerializer(XML)
    //*AFImageResponseSerializer(Image)
    //*AFCompoundResponseSerializer(组合的)
    mgr.responseSerializer = [AFJSONResponseSerializer serializer];
    [mgr POST:url parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [[[AfnHelper alloc] init].hud hide:YES];
        [[[AfnHelper alloc] init].hud removeFromSuperview];
        sucess(responseObject);
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        [[[AfnHelper alloc] init].hud hide:YES];
        [[[AfnHelper alloc] init].hud removeFromSuperview];
        faile(error);
    }];
    
}


#pragma mark 懒加载
- (MBProgressHUD *)hud {
    if (!_hud) {
        _hud = [[MBProgressHUD alloc] initWithView:[[UIApplication sharedApplication].delegate window]];
        _hud.labelText = @"加载中";
        _hud.detailsLabelText = @"字标题";
        //_hud.backgroundColor = [UIColor grayColor];
        _hud.labelColor = [UIColor grayColor];
    }
    return _hud;
}


@end
